<template>
  <div class="editor">
    <div class="title-editor">
      <label>标题</label>
      <el-input
        placeholder="请输入标题"
        class="input-panel"
        v-model="newArticle.title"
      ></el-input>
    </div>
    <mavon-editor
      class="content-editor"
      v-model="newArticle.content"
      @imgAdd="$imgAdd"
      @imgDel="$imgDel"
      @save="saveArticle"
      ref="md"
    ></mavon-editor>
    <el-card class="other-info">
      <div class="upload-cover">
        <label>封面</label>
        <img v-if="coverUrl" :src="coverUrl" class="cover-image" />
        <i v-else class="el-icon-plus cover-uploader-icon"></i>
        <el-button
          class="delete-cover-btn"
          v-if="coverUrl"
          @click="deleteArticleCover"
          >删除封面</el-button
        >
        <div class="upload-btn">
          <input
            type="file"
            ref="cover_upload"
            class="input-file"
            @change="uploadArticleCover"
          />
        </div>
      </div>
      <div class="upload-types">
        <label>标签</label>
        <div class="source">
          <el-tag
            :key="tag"
            v-for="tag in newArticle.type"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-button class="types-btn" v-if="!inputVisible" @click="showInput"
            >+新标签</el-button
          >
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
        </div>
      </div>
    </el-card>
    <el-button type="primary" class="create-btn" @click="addArticle(0)"
      >发布文章</el-button
    >
    <el-button @click="saveArticle" class="save-btn">保存文章</el-button>
  </div>
</template>

<script>
import { api } from "@/api";
import { StoreHandler } from "@/store";
export default {
  data() {
    return {
      value: "",
      title: "",
      img_file: {},
      img_url: {},
      article_id: 0,
      saved: 0,
      newArticle: {
        id: 0,
        aid: 0,
        title: "",
        type: [],
        cover: "",
        abstract: "",
        content: "",
        editing: 1,
      },
      inputVisible: false,
      inputValue: "",
    };
  },
  props: ["articleInfo"],
  watch: {
    articleInfo: function (newVal) {
      this.newArticle = newVal;
      newVal && this.getArticleInfo();
    },
  },
  methods: {
    async saveArticle() {
      this.addArticle(1);
    },
    async addArticle(editing) {
      this.$emit("add-article");
      await this.setArticleId();
      if (!this.newArticle.title || !this.newArticle.content) {
        this.$alert("标题或内容不能为空");
        return;
      }
      if (Object.keys(this.img_file).length !== 0) {
        let length = Object.keys(this.img_file).length;
        for (let i = 1; i < length + 1; i++) {
          this.$refs.md.$img2Url(i, this.img_url[i]);
        }
      }
      try {
        this.newArticle.aid = this.authorId;
        this.newArticle.editing = editing;
        this.newArticle.id = this.article_id;
        this.newArticle.abstract = this.$refs.md.d_render;
        if (this.newArticle.editing == 0) {
          await this.$axios(api.article.addArticle(this.newArticle));
          this.$alert("发布成功!");
          this.$router.push({
            path: "/manager",
            query: { aid: this.authorId },
          });
        } else {
          await this.$axios(api.article.saveArticle(this.newArticle));
          this.$message({
            message: "保存成功!",
            type: "success",
            offset: 60,
          });
        }
      } catch (error) {
        if (error.response) {
          this.$alert(error.response.data.message);
        }
      }
    },
    handleClose(tag) {
      this.newArticle.type.splice(this.newArticle.type.indexOf(tag), 1);
    },
    showInput() {
      if (this.newArticle.type.length > 4) {
        this.$message({
          message: "标签最多只能添加5个",
          type: "warning",
          offset: 60,
        });
        return;
      }
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      let pattern = new RegExp(
        "[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？ ]"
      );
      if (pattern.test(inputValue)) {
        this.$message.error({
          message: "不允许有特殊字符",
          offset: 60,
        });
        return;
      }
      if (inputValue) {
        this.newArticle.type.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 绑定@imgAdd event
    async $imgAdd(pos, $file) {
      await this.setArticleId();
      try {
        await this.$axios(
          api.article.uploadArticleImage($file, this.article_id)
        );
        const url =
          "/api/" +
          api.article.getArticleImage().url +
          `?fileName=${$file.name}&id=${this.article_id}&pos=${pos}`;
        this.$refs.md.$imgUpdateByUrl(pos, url);
        this.img_file[pos] = $file;
        this.img_url[pos] = url;
      } catch (error) {
        if (error.response) {
          this.$alert(error.response.data.message);
        }
      }
    },
    // 绑定@imgDel event
    async $imgDel(pos) {
      let $file = pos[1];
      let fileName = $file.name;
      await this.setArticleId();
      try {
        await this.$axios(
          api.article.deleteArticleImage(fileName, this.article_id)
        );
      } catch (error) {
        if (error.response) {
          console.log(error.response.data.message);
        }
      }
      delete this.img_file[pos[0]];
    },
    // 上传文章封面并获取
    async uploadArticleCover() {
      await this.setArticleId();
      let file = this.$refs.cover_upload.files[0];
      if (!file) {
        return;
      }
      let fileName = this.$refs.cover_upload.files[0].name;
      let suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
      try {
        this.newArticle.cover = this.article_id + "." + suffix;
        await this.$axios(api.article.uploadCover(file, this.article_id));
      } catch (error) {
        if (error.response) {
          this.$alert(error.response.data.message);
        }
      }
      StoreHandler.setters.setEditingCoverUrl(
        "/api/" +
          api.article.getCover(this.article_id, suffix).url +
          `?id=${this.article_id}&suffix=${suffix}` +
          `&random=${Math.random()}`
      );
    },
    // 获取父组件传来的文章信息
    getArticleInfo() {
      this.newArticle = this.articleInfo;
      if (this.newArticle.cover) {
        StoreHandler.setters.setEditingCoverUrl(
          "/api/" +
            api.article.getCover1(this.$route.query.id).url +
            `?random=${Math.random()}`
        );
      } else {
        StoreHandler.setters.setEditingCoverUrl(null);
      }
    },
    // 删除封面
    async deleteArticleCover() {
      await this.setArticleId();
      try {
        await this.$axios(api.article.deleteCover(this.newArticle.cover));
        this.newArticle.cover = "";
        this.$refs.cover_upload.value = "";
      } catch (error) {
        if (error.response) {
          this.$alert(error.response.data.message);
        }
      }
      StoreHandler.setters.setEditingCoverUrl(null);
    },
    // 设置文章id
    async setArticleId() {
      if (!this.articleInfo.id) {
        if (this.article_id !== 0) {
          return;
        }
        this.article_id = (
          await this.$axios(api.article.getMaxArticleId())
        ).data;
        this.article_id = this.article_id + 1;
      } else {
        this.article_id = this.newArticle.id;
      }
    },
  },
  computed: {
    coverUrl() {
      return StoreHandler.getters.getEditingCoverUrl();
    },
    userInfo() {
      return StoreHandler.getters.getUserInfo();
    },
    authorId() {
      return this.userInfo ? this.userInfo.id : 0;
    },
  },
  mounted() {
    if (this.$route.query.id) {
      this.getArticleInfo();
    } else {
      this.newArticle.cover = "";
      this.$refs.cover_upload.value = "";
    }
  },
};
</script>

<style lang="less" scoped>
.editor {
  margin-top: 60px;
  .create-btn {
    width: 200px;
    position: relative;
    margin: 0 auto;
    display: block;
    margin-bottom: 20px;
  }
  .save-btn {
    position: relative;
    display: block;
    margin: 0 auto;
    margin-bottom: 20px;
  }
  .title-editor {
    text-align: center;
    margin-bottom: 20px;
    label {
      padding: 0 20px;
    }
    .input-panel {
      max-width: 1100px;
    }
  }
  .content-editor {
    max-width: 1200px;
    margin: 0 auto;
    min-height: 500px;
  }
  .other-info {
    margin: 0 auto;
    max-width: 1200px;
    margin-top: 20px;
    height: 220px;
    margin-bottom: 20px;
    .upload-cover {
      display: inline-block;
      vertical-align: top;
      label {
        position: absolute;
        font-size: 16px;
        margin: 77px 30px;
      }
      .upload-btn {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        width: 208px;
        height: 178px;
        cursor: pointer;
        display: inline-block;
        margin-left: 100px;
        .input-file {
          cursor: pointer;
          position: relative;
          overflow: hidden;
          opacity: 0;
          width: 208px;
          height: 178px;
        }
      }
      .delete-cover-btn {
        position: absolute;
      }
      .cover-image {
        position: absolute;
        color: #8c939d;
        text-align: center;
        margin-left: 100.6px;
        margin-top: 0.9px;
        cursor: pointer;
        width: 208px;
        height: 178px;
      }
      .cover-uploader-icon {
        position: absolute;
        font-size: 28px;
        color: #8c939d;
        text-align: center;
        margin: 75px 75px 75px 190px;
        cursor: pointer;
      }
      .upload-btn:hover {
        border-color: #409eff;
      }
    }
    .upload-types {
      display: inline-block;
      vertical-align: top;
      margin-left: 150px;
      label {
        font-size: 16px;
        margin: 77px 30px;
      }
      .source {
        .types-btn {
          margin-left: 10px;
          margin-top: 50px;
          height: 32px;
          line-height: 30px;
          padding-top: 0;
          padding-bottom: 0;
        }
        .input-new-tag {
          width: 90px;
          margin-left: 10px;
          margin-top: 50px;
          vertical-align: bottom;
        }
        .el-tag + .el-tag {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
